/*
 * Copyright 2018 the original author or authors.
 * 
 * you can use the file or import project.but Do not take legal responsibility.
 * Only for learning communication.
 *
 * Java compiled version 1.8 or higher
 * 
 * 
 * 
 * 
 */
package org.liang.downimage.ui;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.liang.downimage.config.AppConfig;
import org.liang.downimage.core.DownHtml;
import org.liang.downimage.core.DownImageThread;

/**
 * 网络爬虫程序入口
 * @author houliang
 * @date 2018年1月27日
 */
public class FrameMain {
	
	/**
	 * 程序入口
	 * @param args
	 */
	public static void main(String[] args) {
		FrameMain frame = new FrameMain();
		frame.toshow();
	}

	private JTextField urlTF = new JTextField(20);// 下载网络地址
	private JTextField filePathTF = new JTextField(20);// 保存路径
	private JCheckBox imgCB1 = new JCheckBox(".jpg");
	private JCheckBox imgCB2 = new JCheckBox(".jpeg");
	private JCheckBox imgCB3 = new JCheckBox(".jif");
	private JCheckBox imgCB4 = new JCheckBox(".png");
	private JCheckBox imgCB5 = new JCheckBox(".bmp");
	private JTextField downNumTF = new JTextField(5);// 下载链接数
	private JComboBox<Integer> threadNumCB = new JComboBox<Integer>();//启动线程数
	private JTextArea logTA = new JTextArea(8, 30);// 日志滚动输出
	private String defaultPath = "D://test";
	private String defaultSearchUrl = "http://www.27270.com/";
	public void toshow() {
		JFrame frame = new JFrame();
		frame.setTitle("图片下载");

		//定义组件
		JLabel urlLabel = new JLabel("网络地址");
		JLabel filePathLabel = new JLabel("保存路径");
		JLabel imgLabel = new JLabel("图片类型");//图片类型
		JLabel downNumLabel = new JLabel("下载深度");
		JLabel threadNumLabel = new JLabel("启动线程数");
		JButton selectBtn = new JButton("路径");
		JButton downBtn = new JButton("下载");
		JButton countBtn = new JButton("下载数量");
		JButton clearBtn = new JButton("清空缓存");
				
		//初始化组件
		urlTF.setText(defaultSearchUrl);
		urlTF.setMaximumSize(new Dimension(200, 20));
		filePathTF.setText(defaultPath);
		filePathTF.setMaximumSize(new Dimension(200, 20));
		imgCB1.setSelected(true);
		downNumTF.setMaximumSize(downNumTF.getPreferredSize());
		downNumTF.setText("2");
		threadNumCB.setMaximumSize(threadNumCB.getPreferredSize());
		threadNumCB.addItem(1);
		threadNumCB.addItem(2);
		threadNumCB.addItem(3);
		threadNumCB.addItem(5);
		threadNumCB.addItem(8);
		logTA.setLineWrap(true);// 激活自动换行功能
		logTA.setWrapStyleWord(true);// 激活断行不断字功能
		
		Box hbox1 = Box.createHorizontalBox();// 创建一个水平箱子
		hbox1.add(Box.createHorizontalStrut(20));
		hbox1.add(urlLabel); // 在水平箱子上添加一个标签组件，并且创建一个不可见的、20个单位的组件。在这之后再添加一个文本框组件
		hbox1.add(Box.createHorizontalStrut(10));
		hbox1.add(urlTF);
		hbox1.add(Box.createHorizontalGlue());
	
		Box hbox2 = Box.createHorizontalBox();// 创建一个水平箱子
		hbox2.add(Box.createHorizontalStrut(20));
		hbox2.add(filePathLabel);
		hbox2.add(Box.createHorizontalStrut(10));
		hbox2.add(filePathTF);
		hbox2.add(Box.createHorizontalStrut(10));
		hbox2.add(selectBtn);
		hbox2.add(Box.createHorizontalGlue());
		
		//图片类型
		Box hbox3 = Box.createHorizontalBox();// 创建一个水平箱子
		hbox3.add(Box.createHorizontalStrut(20));
		hbox3.add(imgLabel);
		hbox3.add(Box.createHorizontalStrut(10));
		hbox3.add(imgCB1);
		hbox3.add(imgCB2);
		hbox3.add(imgCB3);
		hbox3.add(imgCB4);
		hbox3.add(imgCB5);
		hbox3.add(Box.createHorizontalGlue());
		
		Box hbox4 = Box.createHorizontalBox();// 创建一个水平箱子
		hbox4.add(Box.createHorizontalStrut(20));
		hbox4.add(downNumLabel);
		hbox4.add(Box.createHorizontalStrut(10));
		hbox4.add(downNumTF);
		hbox4.add(Box.createHorizontalStrut(20));
		hbox4.add(threadNumLabel);
		hbox4.add(Box.createHorizontalStrut(10));
		hbox4.add(threadNumCB);
		hbox4.add(Box.createHorizontalGlue());
		

		Box hbox5 = Box.createHorizontalBox();// 创建一个水平箱子
		hbox5.add(downBtn);
		
		Box hbox6 = Box.createHorizontalBox();// 创建一个水平箱子
		hbox6.add(Box.createHorizontalStrut(10));
		hbox6.add(new JScrollPane(logTA));
		hbox6.add(Box.createHorizontalStrut(10));
		
		Box hbox7 = Box.createHorizontalBox();// 创建一个水平箱子
		hbox7.add(countBtn);
		hbox7.add(clearBtn);
		
		Box vbox = Box.createVerticalBox();
		vbox.add(hbox1);
		vbox.add(hbox2);
		vbox.add(hbox3);
		vbox.add(hbox4);
		vbox.add(hbox5);
		vbox.add(Box.createVerticalStrut(10));
		vbox.add(hbox6);
		vbox.add(Box.createVerticalStrut(10));
		vbox.add(hbox7);

		frame.add(vbox);
		frame.setBounds(400, 200, 400, 400);
		frame.setVisible(true);
		frame.setResizable(false);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// 添加事件
		downBtn.addActionListener(new DownActionListener());
		selectBtn.addActionListener(new SelectFileActionListener());
		countBtn.addActionListener(new CountActionListener());
		clearBtn.addActionListener(new ClearActionListener());
	}

	/*
	 * 点击下载事件
	 */
	class DownActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			setOutPrint();// 设置输出位置：控制台
			long t1 = System.currentTimeMillis();
			try {
				String url = urlTF.getText();
				if (url == null || "".equals(url)) {
					JOptionPane.showMessageDialog(null, "网络地址不能为空");
					return;
				}
				String path = filePathTF.getText();
				if (path == null || path.equals("")) {
					JOptionPane.showMessageDialog(null, "保存文件路径不能为空");
					return;
				}
				int num = 0;
				try {
					num = Integer.parseInt(downNumTF.getText());
				} catch (Exception e1) {
					JOptionPane.showMessageDialog(null, "请输入有效的下载深度");
					return ;
				}
				
				int index = threadNumCB.getSelectedIndex();;
				List<String> selectList = getSelectValue();
				if(selectList.size() ==0) {
					JOptionPane.showMessageDialog(null, "勾选图片类型");
					return;
				}
				AppConfig.searchUrl=url;
				AppConfig.savePath=path;
				AppConfig.pageDepth=num;
				AppConfig.threadNum=index+1;
				AppConfig.imgTypeList=selectList;
				
				logTA.append("正在处理中。。。。\n");
				DownHtml.startDeal();
			} catch (Exception e1) {
				System.out.println("调用异常");
				e1.printStackTrace();
			}
			long t2 = System.currentTimeMillis();
			System.out.println("总用时：" + (t2 - t1));

		}
	}

	/*
	 * 选择文件事件
	 */
	class SelectFileActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			JFileChooser chooser = new JFileChooser(new File(defaultPath));
			chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			int result = chooser.showDialog(new JLabel(), "选择");
			
			File file = chooser.getSelectedFile();
			if(result == 0 && file != null) {
				String path = file.getAbsolutePath();
				filePathTF.setText(path);
			}
		}
	}
	
	/*
	 * 统计下载图片数量事件
	 */
	class CountActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			int imgNum = DownImageThread.imgNum;
			JOptionPane.showMessageDialog(null, "下载图片数量：" + imgNum);
		}
	}
	/*
	 * 清空缓存事件
	 */
	class ClearActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			int result = JOptionPane.showConfirmDialog(null, "清空缓存，可能导致重复下载，是否继续？");
			if(result == 0) {
				DownHtml.visitedUrls.clear();
			}
		}
	}

	/*
	 * 打印日志到，输出文本域
	 */
	public void setOutPrint() {
		try {
			OutputStream output = new OutputStream() {
				@Override
				public void write(int b) throws IOException {
					logTA.append(String.valueOf((char) b));
					logTA.paintImmediately(logTA.getX(), logTA.getY(), logTA.getWidth(), logTA.getHeight());  
				}

				public void write(byte b[]) throws IOException {
					logTA.append(new String(b));
					logTA.paintImmediately(logTA.getX(), logTA.getY(), logTA.getWidth(), logTA.getHeight());  
				}

				public void write(byte b[], int off, int len) throws IOException {
					logTA.append(new String(b, off, len));
					logTA.paintImmediately(logTA.getX(), logTA.getY(), logTA.getWidth(), logTA.getHeight());  
				}

			};
			PrintStream myOut = new PrintStream(output, true);
			System.setOut(myOut);//重定向输出流
			System.setErr(myOut);//重定向错误流

		} catch (Exception e) {
			// multi.close();
			// propFile.close();
			e.printStackTrace();
		}
	}
	
	//获取选中值
	private List<String> getSelectValue(){
		List<String> list = new ArrayList<String>();
		
		if(imgCB1.isSelected()) {
			list.add("jpg");
		}
		if(imgCB2.isSelected()) {
			list.add("jpeg");
		}
		if(imgCB3.isSelected()) {
			list.add("jif");
		}
		if(imgCB4.isSelected()) {
			list.add("png");
		}
		if(imgCB5.isSelected()) {
			list.add("bmp");
		}
		return list;
	}
}
